package com.tuiyun.jxgl;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;

import com.tuiyun.jxgl.bean.Driver;
import com.tuiyun.jxgl.bean.Student;
import com.tuiyun.jxgl.dao.DriverHome;
import com.tuiyun.jxgl.dao.StudentHome;

public class URLSecurity extends AuthorizingRealm {
	
	private StudentHome sh;
	private DriverHome dh;

	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection pc) {
		Object o = pc.fromRealm(getName()).iterator().next();
		if(o instanceof Student){
			Student stu = (Student)o ;
			if(stu.getName().equalsIgnoreCase("admin")){
				SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();			
				info.addRole("admin");			
				return info;
			}else{
				SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();			
				info.addRole("student");			
				return info;
			}	
		}else{
			SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();			
			info.addRole("driver");			
			return info;
		}
			
	}

	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(
			AuthenticationToken at) throws AuthenticationException {
		UsernamePasswordToken usernamePasswordToke = (UsernamePasswordToken)at;		
		String username = usernamePasswordToke.getUsername();
		System.out.println("====================doGetAuthenticationInfo begin ==========================");
		System.out.println("username: " + username);
		System.out.print("password: ");
		System.out.println(usernamePasswordToke.getPassword());
		System.out.println("principal: " + usernamePasswordToke.getPrincipal());
		System.out.println("======================doGetAuthenticationInfo end ========================");		
		Student s = sh.findByUsername(username);		
		if(s != null)
			return new SimpleAuthenticationInfo(s,s.getPwd(), getName());
		Driver d = dh.findByUsername(username);
		if( d != null)
			return new SimpleAuthenticationInfo(d,d.getPwd(), getName());
		else
			return null;
	}

	public StudentHome getSh() {
		return sh;
	}

	public void setSh(StudentHome sh) {
		this.sh = sh;
	}

	public DriverHome getDh() {
		return dh;
	}

	public void setDh(DriverHome dh) {
		this.dh = dh;
	}

}
